package com.genius.adminmanager.menu.service;

import java.sql.SQLException;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.other.entity.DataJson;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.role.entity.RoleJson;
import com.genius.workflow.config.DefaultConfiguration;
import com.genius.workflow.ehcache.CacheUtils;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.GeniusJsonUtil;

public class MenuUtils {
	public static JSONObject getMenuOnceListByRoleId(String roleId,JSONObject response){
		//先根据角色找到权限菜单id
		try {
			JSONArray menuList = getMenuIdsByRole(roleId);
			
			if(menuList.size() == 0){
				response.put(ResponseJson.status, ResponseJson.status_No_Power);
				response.put(ResponseJson.msg, "该角色下没用授权任何模块，请联系管理员授权");
				return response;
			}
			
			String [] menuIds = GeniusJsonUtil.getFieldByDouHaoArr(menuList, MenuJson.menuId);
			String sqlInto = DBTools.getSqlInto(menuList);
			
			//根据权限菜单找到顶层菜单列表
			String menuField = MenuJson.menuId+","+MenuJson.icon+","+MenuJson.name+","+MenuJson.url+","+MenuJson.parentId+","+MenuJson.type;
			String sql = "select "+menuField+" from t_menu where "+MenuJson.status+"=1 and "+MenuJson.state+"=1 and "+MenuJson.menuId+" in ("+sqlInto+") and "+MenuJson.parentId+"='-1' and "+MenuJson.type+"!='button' order by "+MenuJson.place;
//			JSONArray topMenuList = DBUtils.selectArr(sql);
			JSONArray topMenuList = DBTools.selectArr(sql,menuIds);
			JSONArray menuArr = new JSONArray();
			for(int i=0;i<topMenuList.size();i++){
				JSONObject menuJson = new JSONObject();
				menuJson.put(MenuJson.icon, topMenuList.getJSONObject(i).getString(MenuJson.icon));
				menuJson.put(MenuJson.url, topMenuList.getJSONObject(i).getString(MenuJson.url));
				menuJson.put(MenuJson.menuId, topMenuList.getJSONObject(i).getString(MenuJson.menuId));
				menuJson.put(MenuJson.name, topMenuList.getJSONObject(i).getString(MenuJson.name));
				menuJson.put(MenuJson.type, topMenuList.getJSONObject(i).getString(MenuJson.type));
				if(i==0){
					JSONArray subMenu = getOnceMenuById(roleId,topMenuList.getJSONObject(i).getString(MenuJson.menuId));
					menuJson.put("children", subMenu);
				}
				menuArr.add(menuJson);
			}
			
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, menuArr);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "数据库连接失败,请检查");
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "数据库关闭异常");
		} catch (SQLException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "查询菜单出错");
		}
		return response;
	}
	private static JSONArray getMenuIdsByRole(String roleId) throws ConnectionException, DBClosedException, SQLException{
		String selectMenuByRoleId = "select "+MenuJson.menuId+" from t_role_menu where "+RoleJson.roleId+" =? group by "+MenuJson.menuId+"";
		JSONArray menuList = DBTools.selectArr(selectMenuByRoleId, new String[]{roleId});
		return menuList;
	}
	/**
	 * 查询该菜单下data表中要显示的字段
	 */
	public static JSONObject getPowerFileByMenu(String roleId,String menuId,JSONObject response){
		try {
			response.put(ResponseJson.status, ResponseJson.status_Success);
			String queryDataSql = "";
			switch(DefaultConfiguration.geniusDBType){
				case MySql:
				case SqlServer:
					queryDataSql = "select "+DataJson.field+",max(length("+DataJson.field+"))length FROM t_data where "+MenuJson.menuId+"=? and "+RoleJson.roleId+" =? GROUP BY "+DataJson.field;
					break;
				case Oracle:
					queryDataSql = "select to_char("+DataJson.field+")"+DataJson.field+",max(length("+DataJson.field+"))length FROM t_data where "+MenuJson.menuId+"=? and "+RoleJson.roleId+" =? GROUP BY to_char("+DataJson.field+")";
					break;
			}
			JSONObject datas = DBUtils.select(queryDataSql, new String []{menuId,roleId});
			response.put(ResponseJson.data, datas);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "数据库连接失败,请检查");
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "数据库关闭异常");
		} catch (SQLException e) {
			response.put(ResponseJson.status, 1000);
			response.put(ResponseJson.msg, "查询菜单出错");
		}
		return response;
	}
	public static JSONArray getOnceMenuById(String roleId,String menuId) throws ConnectionException, DBClosedException, SQLException{
		
//		String menuField = "b."+MenuJson.menuId+",b."+MenuJson.icon+",b."+MenuJson.name+",b."+MenuJson.url+",b."+MenuJson.parentId+",b."+MenuJson.type;
		String menuField = MenuJson.menuId+","+MenuJson.icon+","+MenuJson.name+","+MenuJson.url+","+MenuJson.canshu+","+MenuJson.parentId+","+MenuJson.type;
		String sql = "select "+menuField+" from t_menu a where "+MenuJson.status+"=1 and "+MenuJson.parentId+"=? and "+MenuJson.type+"!='button' ";
//		String sql = "select "+menuField+" from t_role_menu a left join t_menu b on a."+MenuJson.menuId+"=b."+MenuJson.menuId+" where b."+MenuJson.status+"=1 and a."+RoleJson.roleId+"=? and b."+MenuJson.parentId+"=? and b."+MenuJson.type+"!='button' order by b."+MenuJson.place;
		String sql2 = sql + "and "+ MenuJson.menuId+" in (select "+MenuJson.menuId+" from t_role_menu where "+RoleJson.roleId+"=?) order by "+MenuJson.place;
		JSONArray subMenuList = DBUtils.selectArr(sql2,new String[]{menuId,roleId});
		JSONArray menuArr = new JSONArray();
		for(int index=0;index<subMenuList.size();index++){
			JSONObject subMenu = subMenuList.getJSONObject(index);
			JSONObject subJson = new JSONObject();
			
			subJson.put(MenuJson.url, subMenu.getString(MenuJson.url));
			subJson.put(MenuJson.canshu, subMenu.getString(MenuJson.canshu));
			subJson.put(MenuJson.name, subMenu.getString(MenuJson.name));
			subJson.put(MenuJson.icon, subMenu.getString(MenuJson.icon));
			subJson.put(MenuJson.menuId, subMenu.getString(MenuJson.menuId));
			subJson.put(MenuJson.type, subMenu.getString(MenuJson.type));
			
//			String sqlCount = "select count(1)num from t_role_menu a left join t_menu b on a."+MenuJson.menuId+"=b."+MenuJson.menuId+" where b."+MenuJson.status+"=1 and a."+RoleJson.roleId+"=? and b."+MenuJson.parentId+"=? and b."+MenuJson.type+"!='button' and b."+MenuJson.type+"!='oneToMore' ";
			String sqlCount = "select count(1)num from t_menu where "+MenuJson.status+"=1 and "+MenuJson.parentId+"=? and "+MenuJson.type+"!='button' and "+MenuJson.type+"!='oneToMore' ";
			String sqlCount2 = sqlCount + "and "+ MenuJson.menuId+" in (select "+MenuJson.menuId+" from t_role_menu where "+RoleJson.roleId+"=?)";
			JSONObject haveChildJson = DBUtils.select(sqlCount2,new String[]{subMenu.getString(MenuJson.menuId),roleId});
			
			if(haveChildJson.getInteger("num")==0)
				subJson.put("haveChild", false);
			else{
				subJson.put("haveChild", true);
			}
			menuArr.add(subJson);
		}
		return menuArr;
	}
	/**
	 * 普通添加菜单
	 * @param icon
	 * @param name
	 * @param state
	 * @param url
	 * @param parentId
	 * @param place
	 * @param type
	 * @param createAuthor
	 * @param createTime
	 * @param status
	 * @param setField
	 * @return
	 * @throws ConnectionException
	 * @throws DBClosedException
	 * @throws SQLException
	 */
	public static boolean addMenu(String lastMenuId,String lastPid,String icon,String name,String state,String url,String canshu,String parentId,String place,String type,String createAuthor,String createTime,String status,String setField) throws ConnectionException, DBClosedException, SQLException{
		String field = MenuJson.menuId+","+MenuJson.icon+","+MenuJson.name+","+MenuJson.state+","+MenuJson.url+","+MenuJson.canshu
				+","+MenuJson.parentId+","+MenuJson.place+","+MenuJson.type+","+MenuJson.createAuthor+","+MenuJson.createTime+","+MenuJson.status;
		String insert = DBTools.getInsertSql(field, "t_menu");
		String newMenuId = UUID.randomUUID().toString().replace("-", "");
		String [] parms = new String[]{newMenuId,icon,name,state,url,canshu,parentId,place,type,createAuthor,createTime,status};
		int result [] = DBTools.insert(insert, parms);
		
		boolean isSuccess = result[0]==0?false:true;
		
		insertMenuRAM(null, lastMenuId,"",lastPid,newMenuId, name, parentId);
		
		if(!type.equals("menu"))
			return isSuccess;
    	//向t_menu_field 中插入模块字段
    	JSONObject parmsJson = new JSONObject();
    	parmsJson.put(MenuJson.menuId, newMenuId);
    	parmsJson.put(MenuJson.field, setField);
    	addFieldByMenuId(parmsJson);
    	
		return isSuccess;
	}
	/**
	 * 给该菜单下添加按钮
	 * @param menuId
	 * @param icon
	 * @param name
	 * @param state
	 * @param url
	 * @param parentId
	 * @param place
	 * @param type
	 * @param createAuthor
	 * @param createTime
	 * @param status
	 * @return
	 * @throws ConnectionException
	 * @throws DBClosedException
	 * @throws SQLException
	 */
	public static boolean addMenuBtn(String menuId,String icon,String name,String state,String url,String parentId,String place,String type,String createAuthor,String createTime,String status) throws ConnectionException, DBClosedException, SQLException{
		//保证该菜单下只有一个按钮
		String table = "t_menu";
		String whereField = MenuJson.parentId+","+MenuJson.menuId;
		JSONObject json = new JSONObject();
		json.put(MenuJson.parentId, parentId);
		json.put(MenuJson.menuId, menuId);
		
		JSONObject existsJson = DBTools.getIsExist(whereField, table, json);
		boolean isSuccess = false;
		if(existsJson == null){//不存在再插入
			String field = MenuJson.menuId+","+MenuJson.icon+","+MenuJson.name+","+MenuJson.state+","+MenuJson.url+","+MenuJson.parentId+","+MenuJson.place+","+MenuJson.type+","+MenuJson.createAuthor+","+MenuJson.createTime+","+MenuJson.status;
			String insert = DBTools.getInsertSql(field, table);
			String [] parms = new String[]{menuId,icon,name,state,url,parentId,place,type,createAuthor,createTime,status};
			int result [] = DBTools.insert(insert, parms);
			isSuccess = result[0]==0?false:true;
		}
		return isSuccess;
	}
	/**
	 * 从平台导入菜单信息
	 * @param menuId
	 * @param icon
	 * @param name
	 * @param state
	 * @param url
	 * @param parentId
	 * @param place
	 * @param type
	 * @param createAuthor
	 * @param createTime
	 * @param status
	 * @return
	 * @throws ConnectionException
	 * @throws DBClosedException
	 * @throws SQLException
	 */
	public static boolean addMenuByPlatform(String menuId,String icon,String name,String state,String url,String parentId,String place,String type,String createAuthor,String createTime,String status) throws ConnectionException, DBClosedException, SQLException{
		String field = MenuJson.menuId+","+MenuJson.icon+","+MenuJson.name+","+MenuJson.state+","+MenuJson.url+","+MenuJson.parentId+","+MenuJson.place+","+MenuJson.type+","+MenuJson.createAuthor+","+MenuJson.createTime+","+MenuJson.status;
		String insert = DBTools.getInsertSql(field, "t_menu");
		String [] parms = new String[]{menuId,icon,name,state,url,parentId,place,type,createAuthor,createTime,status};
		int result [] = DBTools.insert(insert, parms);
		boolean isSuccess = result[0]==0?false:true;
		return isSuccess;
	}
	public static boolean addFieldByMenuId(JSONObject json) throws ConnectionException, DBClosedException, SQLException{
		String insertField = MenuJson.menuId+","+MenuJson.field;
		String menu_field_table = "t_menu_field";
    	
		String whereField = MenuJson.menuId;
		
		JSONObject existsJson = DBTools.getIsExist(whereField, menu_field_table, json);
		boolean isSuccess = false;
		if(existsJson == null){//不存在再插入
			int result [] = DBTools.insert(insertField, menu_field_table, json);
			isSuccess = result[0]==0?false:true;
		}
		return isSuccess;
	}
	public static boolean editMenuRAM(JSONArray arr,String menuId,String name,String parentId,String toChangeMenuId,String toChangePid){
		boolean isSuccess = false;
		JSONArray root = arr==null?(JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree):arr;
    	if(root == null){
    		MenuService.loadMenusRAM();
    		root = (JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree);
    	}
    	int size = root.size();
    	//先看是否有编辑
    	for(int index=0;index<size;index++){
    		JSONObject json = root.getJSONObject(index);
    		String menuId_m = json.getString("value");
    		String pId_m = json.getString("pId");
    		if(StringUtils.equals(menuId_m, menuId)&&StringUtils.equals(pId_m, parentId)){
    			if(toChangePid !=null){
    				//如果要跳转的toChangePid不为空，说明要迁移到另一个目录下，那么当前的这个就应该删掉了
    				delMenuRAM(root, menuId_m, parentId);
    			}else{
    				json.put("name", name);
    			}
    			isSuccess = true;
    			return isSuccess;
    		}else{
    			JSONArray children = json.getJSONArray("children");
    			if(children==null){
    				return false;
    			}
    			boolean isSuccessAgain = editMenuRAM(children, menuId, name, parentId,toChangeMenuId,toChangePid);
    			if(isSuccessAgain){
    				return true;
    			}
    		}
    	}
    	if(arr == null){
    		//说明是首次进入的
    		CacheUtils.cacheUtils().addElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree, root);
    	}
    	if(toChangePid !=null){
    		//因为你不知道要跳转到哪个新菜单下面，所以要从头开始循环查询增加
			insertMenuRAM(null, menuId, name, parentId, toChangeMenuId, name, toChangePid);
		}
    	return isSuccess;
	}
	public static boolean insertMenuRAM(JSONArray arr,String lastMenuId,String lastName,String lastPid,String nerMenuId,String newName,String newParentId){
		boolean isSuccess = false;
		JSONArray root = arr==null?(JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree):arr;
    	if(root == null){
    		MenuService.loadMenusRAM();
    		root = (JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree);
    	}
    	int size = root.size();
    	for(int index=0;index<size;index++){
    		JSONObject json = root.getJSONObject(index);
    		String pId_m = json.getString("pId");
    		String menuId_m = json.getString("value");
    		if(StringUtils.equals(menuId_m, lastMenuId)&&StringUtils.equals(pId_m, lastPid)){
    			JSONObject insert = new JSONObject();
    			insert.put("value",nerMenuId);
    			insert.put("name",newName);
    			insert.put("pId",newParentId);
    			JSONArray children = json.getJSONArray("children");
    			if(children == null){
    				children = new JSONArray();
    				json.put("children", children);
    			}
    			children.add(insert);
    			isSuccess = true;
    			return isSuccess;
    		}else{
    			JSONArray children = json.getJSONArray("children");
    			if(children==null){
    				return false;
    			}
    			boolean isSuccessAgain = insertMenuRAM(children, lastMenuId, lastName, lastPid,nerMenuId,newName,newParentId);
    			if(isSuccessAgain){
    				return true;
    			}
    		}
    	}
    	if(arr == null){
    		//说明是首次进入的
    		CacheUtils.cacheUtils().addElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree, root);
    	}
    	return isSuccess;
	}
	public static boolean delMenuRAM(JSONArray arr,String menuId,String parentId){
		boolean isSuccess = false;
		JSONArray root = arr==null?(JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree):arr;
    	if(root == null){
    		MenuService.loadMenusRAM();
    		root = (JSONArray)CacheUtils.cacheUtils().getElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree);
    	}
    	int size = root.size();
    	int delIndex = -1;
    	for(int index=0;index<size;index++){
    		JSONObject json = root.getJSONObject(index);
    		String pId_m = json.getString("pId");
    		String menuId_m = json.getString("value");
    		if(StringUtils.equals(menuId_m, menuId)&&StringUtils.equals(pId_m, parentId)){
    			delIndex = index;
    			break;
    		}else{
    			JSONArray children = json.getJSONArray("children");
    			if(children==null){
    				return false;
    			}
    			boolean isSuccessAgain = delMenuRAM(children, menuId, parentId);
    			if(isSuccessAgain){
    				return true;
    			}
    		}
    	}
    	if(delIndex != -1){
    		root.remove(delIndex);
    		isSuccess = true;
    	}
    	if(arr == null){
    		//说明是首次进入的
    		CacheUtils.cacheUtils().addElement(DefaultConfiguration.menuRAM, DefaultConfiguration.menuRAM_tree, root);
    	}
    	return isSuccess;
	}
	public static void editorMenu(JSONObject json,String table,String whereField,String menuId,String name,String pId,String toChangeMenuId,String toChangePid) throws ConnectionException, DBClosedException, SQLException{
		String updateField = MenuJson.name+","+MenuJson.icon+","+MenuJson.type+","+MenuJson.url+","+MenuJson.canshu
				+","+MenuJson.place+","+MenuJson.createAuthor+","+MenuJson.createTime+","+MenuJson.status+","+MenuJson.parentId;
		String updateSql = DBTools.getUpdateAndWhereSql(updateField, table, whereField);
		
		if(toChangeMenuId != null){
			String [] parms = DBTools.getUpdateAndWhereParms(updateField, json, whereField);
			parms[parms.length-3] =toChangeMenuId; 
			
			DBTools.update(updateSql,parms);
		}else{
			DBTools.update(updateField, whereField, table, json);
		}
		MenuUtils.editMenuRAM(null, menuId, name, pId,toChangeMenuId,toChangePid);
		String type = json.getString(MenuJson.type);
		if(type.equals("menu")){
			String keywords = MenuJson.menuId;
			JSONObject menu_fieldJson = DBTools2.getIsExist(keywords,"t_menu_field",json);
			if(menu_fieldJson != null){
				String t_menu_field = MenuJson.field;
				String where_t_menu_field = MenuJson.menuId;
				String menu_field_table = "t_menu_field";
		    	DBTools.update(t_menu_field, where_t_menu_field, menu_field_table, json);
			}else{
				String t_menu_field = MenuJson.menuId+","+MenuJson.field;
				String menu_field_table = "t_menu_field";
		    	DBTools.insert(t_menu_field,menu_field_table, json);
			}
			
		}
	}
}
